package com.retoc.oawx.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.retoc.oawx.common.util.R;
import com.retoc.oawx.config.shiro.JWTUtil;
import com.retoc.oawx.domain.Meeting;
import com.retoc.oawx.domain.req.*;
import com.retoc.oawx.exception.OAException;
import com.retoc.oawx.service.MeetingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("/meeting")
@Api("会议模块接口")
@Slf4j
public class MeetingController {
    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private MeetingService meetingService;

    @PostMapping("/searchMyMeetingListByPage")
    @ApiOperation("查询会议列表分页数据")
    public R searchMyMeetingListByPage(@Valid @RequestBody PageReq req, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        Integer page = req.getPage();
        Integer length = req.getLength();
        int start = (page - 1) * length;
        HashMap map = new HashMap<>();
        map.put("userId", userId);
        map.put("start", start);
        map.put("length", length);
        ArrayList<HashMap> result = meetingService.searchMyMeetingByPage(map);
        return R.ok().put("result", result);
    }

    @PostMapping("/insertMeeting")
    @ApiOperation("添加会议")
    @RequiresPermissions(value = {"ROOT","MEETING:INSERT"},logical = Logical.OR)
    public R insertMeeting(@Valid @RequestBody CreateMeetingReq req, @RequestHeader("token") String token) {
        if (req.getType() == 2 && (req.getPlace() == null || req.getPlace().length() == 0)) {
            throw new OAException("地点不能为空");
        }
        DateTime d1 = DateUtil.parse(req.getDate() + " " + req.getStart() + ":00");
        DateTime d2 = DateUtil.parse(req.getDate() + " " + req.getEnd() + ":00");
        if (d2.isBeforeOrEquals(d1)) {
            throw new OAException("结束时间必须大于开始时间");
        }
        if (!JSONUtil.isJsonArray(req.getMembers())) {
            throw new OAException("member不是JSON数组");
        }
        Meeting meeting = new Meeting();
        meeting.setUuid(UUID.randomUUID().toString(true));
        meeting.setTitle(req.getTitle());
        meeting.setCreatorId(jwtUtil.getUserId(token));
        meeting.setDate(req.getDate());
        meeting.setPlace(req.getPlace());
        meeting.setStart(req.getStart()+":00");
        meeting.setEnd(req.getEnd()+":00");
        meeting.setType((int)req.getType());
        meeting.setMembers(req.getMembers());
        meeting.setDesc(req.getDesc());
        meeting.setStatus(0);
        meetingService.insertMeeting(meeting);
        return R.ok().put("result","success");
    }

    @PostMapping("searchMeetingById")
    @ApiOperation("查询会议")
    @RequiresPermissions(value = {"ROOT","MEETING:SELECT"},logical = Logical.OR)
    public R searchMeetingById(@Valid @RequestBody MeetingReq req){
        HashMap map = meetingService.searchMeetingById(req.getId());
        return R.ok().put("result", map);
    }

    @PostMapping("/updateMeetingInfo")
    @ApiOperation("更新会议")
    @RequiresPermissions(value = {"ROOT", "MEETING:UPDATE"}, logical = Logical.OR)
    public R updateMeetingInfo(@Valid @RequestBody UpdateMeetingReq req) {
        if (req.getType() == 2 && (req.getPlace() == null || req.getPlace().length() == 0)) {
            throw new OAException("线下会议地点不能为空");
        }
        DateTime d1 = DateUtil.parse(req.getDate() + " " + req.getStart() + ":00");
        DateTime d2 = DateUtil.parse(req.getDate() + " " + req.getEnd() + ":00");
//        long hours = d1.between(d2, DateUnit.HOUR);
        if (d2.isBeforeOrEquals(d1)) {
            throw new OAException("结束时间必须大于开始时间");
        }
        if (!JSONUtil.isJsonArray(req.getMembers())) {
            throw new OAException("members不是JSON数组");
        }
        HashMap param = new HashMap();
        param.put("title", req.getTitle());
        param.put("date", req.getDate());
//        param.put("hours", hours);
        param.put("place", req.getPlace());
        param.put("start", req.getStart() + ":00");
        param.put("end", req.getEnd() + ":00");
        param.put("type", req.getType());
        param.put("members", req.getMembers());
        param.put("desc", req.getDesc());
        param.put("id", req.getId());
        param.put("instanceId", req.getInstanceId());
        param.put("status", 1);
        meetingService.updateMeetingInfo(param);
        return R.ok().put("result", "success");
    }

    @PostMapping("/deleteMeetingById")
    @ApiOperation("根据ID删除会议")
    @RequiresPermissions(value = {"ROOT", "MEETING:DELETE"}, logical = Logical.OR)
    public R deleteMeetingById(@Valid @RequestBody MeetingReq req) {
        meetingService.deleteMeetingById(req.getId());
        return R.ok().put("result", "success");
    }

    @PostMapping("/receiveNotify")
    @ApiOperation("接受工作流通知")
    public R recieveNotify(@Valid @RequestBody RecieveNotifyReq req) {
        System.out.println("成功同意！");
        if (req.getResult().equals("同意")) {
            log.debug(req.getUuid() + "的会议审批通过");
        } else {
            log.debug(req.getUuid() + "的会议审批不通过");
        }
        return R.ok();
    }

    @PostMapping("/recNotify")
    @ApiOperation("接收审批信息")
    public void receiveNotify(@Valid @RequestBody NotifyReq req) {

        System.out.println("成功接收："+req.getInstanceId());

    }
}
